package com.hunan.api.catv.service.impl.tencent_cloud.vod;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Random;

@Service
public class SignatureService {

    public static Logger log = LoggerFactory.getLogger(SignatureService.class);

    private static final String HMAC_ALGORITHM = "HmacSHA1";
    private static final String CONTENT_CHARSET = "UTF-8";

    public static byte[] byteMerger(byte[] byte1, byte[] byte2) {
        byte[] byte3 = new byte[byte1.length + byte2.length];
        System.arraycopy(byte1, 0, byte3, 0, byte1.length);
        System.arraycopy(byte2, 0, byte3, byte1.length, byte2.length);
        return byte3;
    }

    public String getUploadSignature(String secretId, String secretKey, String procedure) {
        String strSign = "";
        String contextStr = "";
        try {
            long endTime = (System.currentTimeMillis() / 1000 + 3600 * 24);
            contextStr += "secretId=" + java.net.URLEncoder.encode(secretId, "utf8");
            contextStr += "&currentTimeStamp=" + System.currentTimeMillis() / 1000;
            contextStr += "&expireTime=" + endTime;
            contextStr += "&random=" + new Random().nextInt(java.lang.Integer.MAX_VALUE);
            contextStr += "&procedure=" + procedure;
            Mac mac = Mac.getInstance(HMAC_ALGORITHM);
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(CONTENT_CHARSET), mac.getAlgorithm());
            mac.init(secretKeySpec);

            byte[] hash = mac.doFinal(contextStr.getBytes(CONTENT_CHARSET));
            byte[] sigBuf = byteMerger(hash, contextStr.getBytes("utf8"));
            strSign = base64Encode(sigBuf);
            strSign = strSign.replace(" ", "").replace("\n", "").replace("\r", "");
        } catch (Exception e) {
            log.error("[VodSign-Error:" + e.toString() + "]");
        }
        return strSign;
    }

    private static String base64Encode(byte[] buffer) {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(buffer);
    }
}
